import axios, { type AxiosRequestHeaders } from "axios"
import storage from "./storage"
import { showToast } from 'vant';
import router from "../router";
import { useAppStore } from '@/store/useAppStore';
const appStore = useAppStore();
const { changeIsLoading } = appStore
const instance = axios.create({
    baseURL: import.meta.env.VITE_URL,
    timeout: 10000,
})
var gconfig = {} as any;
instance.interceptors.request.use(
    function (config: any) {
        gconfig = config
        if (!config.headers) {
            config.headers = {} as AxiosRequestHeaders
        }
        if (storage.get("token")) {
            config.headers.authorization = `Bearer ${storage.get("token")}`
        }
        changeIsLoading(true)
        return config
    },
    function (error: any) {
        changeIsLoading(false)
        return Promise.reject(error)
    }
)
instance.interceptors.response.use(
    async function (response: any) {
        changeIsLoading(false)
        if (response.data.code == 200) {
            return response.data
        }
        if (response.data.code == 100) {
            return response.data
        }
        if (response.data.code == 401) {
            storage.deleteKey('token')
            router.replace('/login')
            showToast("认证已过期,请重新登录")
            return Promise.reject(response.data)
        } else {
            if (import.meta.env.MODE == 'development') {
                showToast(`url:${gconfig.url}=>请求失败`)
            }
            return Promise.reject(response.data)
        }
    },
    function (error: any) {
        if (error.code == "ERR_NETWORK" || error.code == "ECONNABORTED") {
            return showToast("服务器网络异常,请连接网络刷新后重试")
        }
        if (error.response) {
        }
        changeIsLoading(false)
        return Promise.reject(error)
    }
)


export { instance }
